import {getUserPhone} from "@src/api/base";
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import base from "@src/store/base";

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }],
  data: {
    visible: false,
    auto: false,
    text: '',
    reject: null,
    resolve: null,
  },
  methods: {
    open(options) {
      let {text, auto} = options;
      if (!text) {
        text = "获取手机号"
      }
      return new Promise((resolve, reject) => {
        this.setData({visible: true, resolve, reject, text, auto})
      })
    },
    close() {
      this.setData({visible: false, resolve: null, reject: null})
    },
    handleStop() {
      return true;
    },
    handleCancel() {
      this.data.reject && this.data.reject()
      this.close();
    },
    handleGetPhoneNumber(e) {
      if (!e.detail.iv) {
        wx.showToast({title: "手机号获取失败，请重试", icon: "none", duration: 3000});
        return;
      }
      let data = {
        ivStr: e.detail.iv,
        encryptedData: e.detail.encryptedData,
      }
      if (!this.data.auto) {
        this.data.resolve  && this.data.resolve(data);
        this.close();
        return;
      }
      // 自动解析手机号
      getUserPhone(data).then(res => {
        if (res.code === 0) {
          this.data.resolve  && this.data.resolve(res.data);
          this.close();
        } else {
          wx.showToast({title: "手机号获取失败，请重试", icon: "none", duration: 3000});
        }
      })
    },
  }
});
